const Router = require('koa-router');
const matchCtl= require('../../controllers/matches.js')
const teamCtl= require('../../controllers/teams.js')
const cmptCtl= require('../../controllers/competitions.js')
const MtmCtl= require('../../controllers/matchteams.js')
const playerCtl= require('../../controllers/players.js')
const MplCtl= require('../../controllers/matchplayers.js')
const eventCtl= require('../../controllers/events.js')
const coachCtl= require('../../controllers/coaches.js')
const teafeaCtl= require('../../controllers/teamfeatures.js')
const plyfeaCtl= require('../../controllers/playerfeatures.js')
const router = new Router();

/**
 * @swagger
 * tags:
 *   - name: match
 *     description: Everything about match
 */

router
/**
 * @swagger
 * paths:
 *   /matches:
 *     get:
 *       tags:
 *         - match
 *       summary: Return a list of matches
 *       description: ''
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             type: array
 *             items:
 *               $ref: '#/definitions/match'
 */
    .get('/', async (ctx, next)=>{ ctx.body = await matchCtl.list(); })

/**
 * @swagger
 * paths:
 *   /matches:
 *     post:
 *       tags:
 *         - match
 *       summary: Create a match
 *       description: ''
 *       parameters:
 *         - in: body
 *           name: "body"
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/match"
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .post('/', async (ctx, next)=>{
        const {id} = ctx.params;
        const data = ctx.request.body;
        let  r = await matchCtl.create(data);
        ctx.body = r;
    })
/**
 * @swagger
 * paths:
 *   /matches/{id}:
 *     get:
 *       tags:
 *         - match
 *       summary: Return a match
 *       description: ''
 *       parameters:
 *         - in: path
 *           name: id 
 *           description: ""
 *           required: true
 *           type: string
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             $ref: '#/definitions/match'
 */
    .get('/:id', async (ctx, next)=>{
        // Retrieves informations about a given match
        const {id} = ctx.params;
        const r = await matchCtl.retrieve(id);
        ctx.assert(r !== null, 404, 'Detail not found!');

        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /matches/{id}:
 *     put:
 *       tags:
 *         - match
 *       summary: Update or create a match
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: id 
 *           description: ""
 *           required: true
 *           type: string
 *         - in: body
 *           name: body
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/match"
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .put('/:id', async (ctx, next)=>{
        const id = ctx.params.id;
        const data = ctx.request.body;
        const r = await matchCtl.upsert(id, data);
        
        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /matches/{id}:
 *     delete:
 *       tags:
 *         - match
 *       summary: Delete a match
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: id 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         204:
 *           description: No content
 */
    .delete('/:id', async (ctx, next)=>{
        matchCtl.removeById(ctx.params.id);
        ctx.status = 204;
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}/seasons:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return the list of seasons of the given competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:id/seasons', async (ctx, next)=>{
        const {id} = ctx.params;
        ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);
    })

    .get('/aboutmatches/scorelist/:competitionid/:seasonid', async (ctx, next)=>{
        const {competitionid, seasonid} = ctx.params;
        const r = await teamCtl.find();
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        var objectArraySort = function (keyname1) {
            return function (objectN, objectM){
                var valueN = objectN[keyname1]
                var valueM = objectM[keyname1]
                if (valueN < valueM) return 1
                else if  (valueN > valueM) return -1
                else  return 0
            }
        }
        /*async function compare() {}

        async function bubbleSort(arr) {
            var len = arr.length;
            for (var i = 0; i < len; i++) {
                for (var j = 0; j < len - 1 - i; j++) {
                    var isAbove = await compare(array[j], array[j+1]);
                    if (isAbove) {        //相邻元素两两对比
                        var temp = arr[j+1];        //元素交换
                        arr[j+1] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
            return arr;
        }
        async function mysort(a,b){
            if (a['points'] == b['points']){
                const matchOne = async () => { 
                    const x = await matchCtl.find({home_team_id: a['teamId'], away_team_id: b['teamId'], season: seasonid, competitionId: competitionid});
                    //console.log(x);
                    return x;
                }                              
                /*const matchTwo = async () => { 
                    const y = await matchCtl.find({home_team_id: b['teamId'], away_team_id: a['teamId'], season: seasonid, competitionId: competitionid});
                    return y;
                }
                let a_score = 0, b_score = 0;
                //match1().then(res => console.log(res))
                //let matchOne = res;
                //let matchOne = match1()
                //matchOne()
                const xxx = await matchOne()
                //const match2 = await matchTwo()
                console.log(xxx)
                for (let c of match1){
                    if (c.home_score > c.away_score){
                        a_score = a_score + 3
                        b_score = b_score + 0
                    }
                    else if (c.home_score < c.away_score){
                        a_score = a_score + 0
                        b_score = b_score + 3
                    }
                    else {
                        a_score = a_score + 1
                        b_score = b_score + 1
                    }
                }
                for (let d of match2){
                    if (d.home_score > d.away_score){
                        a_score = a_score + 0
                        b_score = b_score + 3
                    }
                    else if (d.home_score < d.away_score){
                        a_score = a_score + 3
                        b_score = b_score + 0
                    }
                    else {
                        a_score = a_score + 1
                        b_score = b_score + 1
                    }
                }
                if (a_score == b_score){
                    if (a['difference'] == b['difference']){
                        if (a['goal'] > b['goal']){
                            return 1;
                        }
                        else if(a['goal'] == b['goal']){
                            return 0;
                        }
                        else {
                            return -1;
                        }
                    }
                    else {
                        if (a['difference'] > b['difference']){
                            return 1;
                        }
                        else {
                            return -1;
                        }
                    }
                }
                else {
                    if (a_score > b_score){
                        return 1;
                    }
                    else {
                        return -1;
                    }
                }
            }
            else {
                if (a['points'] > b['points']) {
                    return 1;
                }
                else {
                    return -1;
                }
            }
            /*if (a.age !== b.age) return a.age < b.age ? -1 : 1
            else if (a.id !== b.id) return a.id < b.id ? -1 : 1
            else if (a.name !== b.name) return a.name < b.name ? -1 : 1
        }*/
        let Result = []
        for (let a of r){
            //let win = 0, draw = 0, lose = 0, goal = 0, conceded = 0;
            teamId = a.teamId
            //console.log(teamId)
            const match = await matchCtl.find({$or:[{home_team_id: teamId},{away_team_id: teamId}], season: seasonid, competitionId: competitionid});
            //console.log(matches)
            if (match.length != 0){
                let matches = match;
                matches = matches.sort(compare('round'))
                //console.log(matches)
                let obj = {}, recentresult = [], win = 0, draw = 0, lose = 0, goal = 0, conceded = 0, i = 0;
                for (let b of matches){
                    if (i < 5){
                        let obj1 = {}
                        obj1.matchId = b.matchId;
                        obj1.battle = b.label;
                        if (b.home_team_id == teamId){
                            if (b.home_score > b.away_score){
                                obj1.result = 1
                            }
                            else if (b.home_score == b.away_score){
                                obj1.result = 2
                            }
                            else if (b.home_score < b.away_score){
                                obj1.result = 3
                            }
                        }
                        else if (b.away_team_id == teamId){
                            if (b.home_score > b.away_score){
                                obj1.result = 3
                            }
                            else if (b.home_score == b.away_score){
                                obj1.result = 2
                            }
                            else if (b.home_score < b.away_score){
                                obj1.result = 1
                            }
                        }
                        i++;
                        recentresult.push(obj1)
                    }
                    if (b.home_team_id == teamId){
                        goal = goal + b.home_score;
                        conceded = conceded + b.away_score;
                        if (b.home_score > b.away_score){
                            win = win + 1
                        }
                        else if (b.home_score == b.away_score){
                            draw = draw + 1
                        }
                        else if (b.home_score < b.away_score){
                            lose = lose + 1
                        }
                    }
                    else if (b.away_team_id == teamId){
                        goal = goal + b.away_score;
                        conceded = conceded + b.home_score;
                        if (b.home_score > b.away_score){
                            lose = lose + 1
                        }
                        else if (b.home_score == b.away_score){
                            draw = draw + 1
                        }
                        else if (b.home_score < b.away_score){
                            win = win + 1
                        }
                    }
                }
                obj.teamId = teamId;
                for (let key of Object.keys(a['name'])){
                    if (key == seasonid){
                        let team = a['name'][key]
                        obj.teamName = team.offcialName.slice(0,4);
                        obj.img = team.teamImg;
                    }
                }
                obj.games = win + draw + lose;
                obj.win = win;
                obj.draw = draw;
                obj.lose = lose;
                obj.goal = goal;
                obj.conceded = conceded;
                obj.difference = goal - conceded;
                obj.points = win * 3 + draw;
                obj.recentResult = recentresult;
                Result.push(obj)
            }
            else {
                continue;
            }
        }
        Result = Result.sort(objectArraySort('points'));
        //Result = Result.sort(mysort)
        let result =[], i = 1;
        for (let a of Result){
            let obj = {}
            obj.rank = i;
            obj.teamId = a.teamId;
            obj.teamName = a.teamName;
            obj.img = a.img;
            obj.games = a.games;
            obj.win = a.win;
            obj.draw = a.draw;
            obj.lose = a.lose;
            obj.goal = a.goal;
            obj.conceded = a.conceded;
            obj.difference = a.difference;
            obj.points = a.points;
            obj.recentResult = a.recentResult;
            result.push(obj);
            i++;
        }
        ctx.body = result;
    })

    .get('/aboutmatches/matchlist/:competitionid/:seasonid', async (ctx, next)=>{
        const {competitionid, seasonid} = ctx.params;
        const matches = await matchCtl.find({season: seasonid, competitionId: competitionid});
        let result = []
        for (let a of matches){
            let obj = {};
            obj.round = a.round;
            obj.matchId = a.matchId;
            const home = await teamCtl.find({teamId: a.home_team_id})
            for (let b of home){
                for (let key of Object.keys(b['name'])){
                    if (key == seasonid){
                        let team = b['name'][key];
                        obj.homeTeamId = a.home_team_id;
                        obj.homeTeam = team.offcialName.slice(0,4);
                        obj.homeTeamImg = team.teamImg;
                    }
                }
            }
            const away = await teamCtl.find({teamId: a.away_team_id})
            for (let c of away){
                for (let key of Object.keys(c['name'])){
                    if (key == seasonid){
                        let team = c['name'][key];
                        obj.awayTeamId = a.away_team_id;
                        obj.awayTeam = team.offcialName.slice(0,4);
                        obj.awayTeamImg = team.teamImg;
                    }
                }
            }
            obj.score = a.home_score + "-" + a.away_score;
            obj.matchTime = a.match_time.slice(0,-3);
            const h = await teamCtl.find({teamId: a.home_team_id})
            for (let b of h){
                obj.stadium = b.stadiumName + ',' + b.city;
            }
            result.push(obj)
        }
        ctx.body = result;
    })

    .get('/aboutmatches/ranklist/:competitionid/:seasonid', async (ctx, next)=>{
        const {competitionid, seasonid} = ctx.params;
        const rank = await teafeaCtl.find();
        var objectArraySort = function (keyname1) {
            return function (objectN, objectM){
                var valueN = objectN[keyname1]
                var valueM = objectM[keyname1]
                if (valueN < valueM) return 1
                else if  (valueN > valueM) return -1
                else  return 0
            }
        }
        //console.log(rank);
        let result = [];
        for (let a of rank){
            for(let key of Object.keys(a)) {
                //console.log(key);
                if (key == competitionid){
                    let d = a[key];
                    for (let key1 of Object.keys(d)){
                        let teamrank = d[key1]
                        if (key1 == seasonid){
                            let obj = {}, win = 0, draw = 0, lose = 0;
                            const match = await matchCtl.find({$or:[{home_team_id: a.teamId},{away_team_id: a.teamId}], season: seasonid, competitionId: competitionid});
                            for (let b of match){
                                if (b.home_team_id == a.teamId){
                                    //goal = goal + b.home_score;
                                    //conceded = conceded + b.away_score;
                                    if (b.home_score > b.away_score){
                                        win = win + 1
                                    }
                                    else if (b.home_score == b.away_score){
                                        draw = draw + 1
                                    }
                                    else if (b.home_score < b.away_score){
                                        lose = lose + 1
                                    }
                                }
                                else if (b.away_team_id == a.teamId){
                                    //goal = goal + b.away_score;
                                    //conceded = conceded + b.home_score;
                                    if (b.home_score > b.away_score){
                                        lose = lose + 1
                                    }
                                    else if (b.home_score == b.away_score){
                                        draw = draw + 1
                                    }
                                    else if (b.home_score < b.away_score){
                                        win = win + 1
                                    }
                                }
                            }
                            obj.teamId = a.teamId;
                            const teams = await teamCtl.find({teamId: a.teamId})
                            for (let c of teams){
                                for (let key2 of Object.keys(c['name'])){
                                    if (key2 == seasonid){
                                        let team = c['name'][key2]
                                        obj.teamName = team.offcialName.slice(0,4);
                                        obj.teamImg = team.teamImg
                                    }
                                }
                            }
                            obj.seasonScore = win * 3 + draw;
                            obj.totalScore = parseFloat(teamrank['totalScore'].toFixed(2));
                            obj.attackScore = parseFloat(teamrank['attackScore'].toFixed(2));
                            obj.defenseScore = parseFloat(teamrank['defenseScore'].toFixed(2));
                            obj.organizeScore = parseFloat(teamrank['organizeScore'].toFixed(2));
                            obj.skillScore = parseFloat(teamrank['skillScore'].toFixed(2));
                            obj.setScore = parseFloat(teamrank['setScore'].toFixed(2));
                            obj.passScore = parseFloat(teamrank['passScore'].toFixed(2));
                            result.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
            //break;
        }
        result = result.sort(objectArraySort('seasonScore'));
        let Result = [], i = 1;
        for (let a of result){
            let obj = {};
            obj.rank = i;
            obj.teamId = a.teamId;
            obj.teamName = a.teamName;
            obj.teamImg = a.teamImg;
            obj.seasonScore = a.seasonScore;
            obj.totalScore = a.totalScore;
            obj.attackScore = a.attackScore;
            obj.defenseScore = a.defenseScore;
            obj.organizeScore = a.organizeScore;
            obj.skillScore = a.skillScore;
            obj.setScore = a.setScore;
            obj.passScore = a.passScore;
            Result.push(obj);
            i++;
        }
        ctx.body = Result;
    })

    .get('/aboutmatches/shoterlist/:competitionid/:seasonid', async (ctx, next)=>{
        const {competitionid, seasonid} = ctx.params;
        const players = await plyfeaCtl.find();
        //console.log(player)
        var objectArraySort = function (keyname1) {
            return function (objectN, objectM){
                var valueN = objectN[keyname1]
                var valueM = objectM[keyname1]
                if (valueN < valueM) return 1
                else if  (valueN > valueM) return -1
                else  return 0
            }
        }
        let Result = [];
        for (let a of players){
            for(let key of Object.keys(a)) {
                if (key == competitionid){
                    let e = a[key];
                    for (let key1 of Object.keys(e)){
                        let player = e[key1]
                        if (key1 == seasonid){
                            let obj = {};
                            obj.rank = 0;
                            /*const p = await playerCtl.find({playerId: a.playerId});
                            for (let b of p){
                                obj.playerName = b.playerName;
                                //obj.playerId = a.playerId;
                            }*/
                            obj.playerId = a.playerId;
                            obj.playerName = 0;
                            obj.playerImg = 0;
                            obj.teamId = player['teamId'];
                            obj.teamName = 0;
                            obj.teamImg = 0;
                            /*const t = await teamCtl.find({teamId: player['teamId']})
                            for (let c of t){
                                for (let key4 of Object.keys(c['name'])){
                                    if (key4 == seasonid){
                                        let team = c['name'][key4]
                                        obj.teamName = team.offcialName.slice(0,4);
                                        obj.teamImg = team.teamImg;
                                    }
                                }
                                //obj.teamName = c.Chinese_name
                            }*/
                            obj.allScore = player['totalGoal'];
                            obj.ordinaryScore = player['ordinaryGoal'];
                            obj.penalty = player['penalty']
                            obj.teamScore = 0;
                            /*const teamfeature = await teafeaCtl.find({teamId: player['teamId']});
                            for (let d of teamfeature){
                                for (let key2 of Object.keys(d)){
                                    if (key2 == competitionid){
                                        let f = d[key2];
                                        for (let key3 of Object.keys(f)){
                                            let team = f[key3]
                                            if (key3 == seasonid){
                                                obj.teamScore = team['totalGoal'];
                                            }
                                            else {
                                                continue;
                                            }
                                        }
                                    }
                                    else {
                                        continue;
                                    }
                                }
                            }*/
                            Result.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        Result = Result.sort(objectArraySort('allScore'));
        let result = [], i = 1;
        for (let a of Result){
            if (i <= 15){
                a.rank = i;
                const p = await playerCtl.find({playerId: a.playerId});
                for (let b of p){
                    a.playerName = b.playerName;
                    a.playerImg = b.playerImg;
                    //obj.playerId = a.playerId;
                }
                const t = await teamCtl.find({teamId: a['teamId']})
                for (let c of t){
                    for (let key4 of Object.keys(c['name'])){
                        if (key4 == seasonid){
                            let team = c['name'][key4]
                            a.teamName = team.offcialName.slice(0,4);
                            a.teamImg = team.teamImg;
                        }
                    }
                    //obj.teamName = c.Chinese_name
                }
                const teamfeature = await teafeaCtl.find({teamId: a['teamId']});
                for (let d of teamfeature){
                    for (let key2 of Object.keys(d)){
                        if (key2 == competitionid){
                            let f = d[key2];
                            for (let key3 of Object.keys(f)){
                                let team = f[key3]
                                if (key3 == seasonid){
                                    a.teamScore = team['totalGoal'];
                                }
                                else {
                                    continue;
                                }
                            }
                        }
                        else {
                            continue;
                        }
                    }
                }
                a.scoreRatio = (a.allScore / a.teamScore * 100).toFixed() + '%';
                result.push(a);
                /*let obj = {};
                obj.rank = i;
                obj.playerId = a.playerId;
                obj.playerName = a.playerName;
                obj.teamId = a.teamId;
                obj.teamName = a.teamName;
                obj.teamImg = a.teamImg;
                obj.allScore = a.allScore;
                obj.ordinaryScore = a.ordinaryScore;
                obj.penalty = a.penalty;
                obj.teamScore = a.teamScore;
                obj.scoreRatio = (a.allScore / a.teamScore * 100).toFixed() + '%';
                result.push(obj);*/
                i++;
            }
            else {
                break;
            }
        }
        ctx.body = result;
    })

    .get('/aboutmatches/assistlist/:competitionid/:seasonid', async (ctx, next)=>{
        const {competitionid, seasonid} = ctx.params;
        const players = await plyfeaCtl.find();
        //console.log(player)
        var objectArraySort = function (keyname1) {
            return function (objectN, objectM){
                var valueN = objectN[keyname1]
                var valueM = objectM[keyname1]
                if (valueN < valueM) return 1
                else if  (valueN > valueM) return -1
                else  return 0
            }
        }
        let Result = [];
        for (let a of players){
            for(let key of Object.keys(a)) {
                if (key == competitionid){
                    let e = a[key]
                    for (let key1 of Object.keys(e)){
                        let player = e[key1];
                        if (key1 == seasonid){
                            let obj = {};
                            obj.rank = 0;
                            /*const p = await playerCtl.find({playerId: a.playerId});
                            for (let b of p){
                                obj.playerName = b.playerName;
                            }*/
                            obj.playerId = a.playerId;
                            obj.playerName = 0;
                            obj.playerImg = 0;
                            obj.teamId = player['teamId']
                            obj.teamName = 0;
                            obj.teamImg = 0;
                            /*const t = await teamCtl.find({teamId: player['teamId']})
                            for (let c of t){
                                for (let key4 of Object.keys(c['name'])){
                                    if (key4 == seasonid){
                                        let team = c['name'][key4]
                                        obj.teamName = team.offcialName.slice(0,4);
                                        obj.teamImg = team.teamImg;
                                    }
                                }
                            }*/
                            obj.assists = player['totalAssist'];
                            obj.setAssists = player['setAssist'];
                            //obj.penalty = player['penalty']
                            obj.teamAssists = 0;
                            /*const teamfeature = await teafeaCtl.find({teamId: player['teamId']});
                            for (let d of teamfeature){
                                for (let key2 of Object.keys(d)){
                                    if (key2 == competitionid){
                                        let f = d[key2];
                                        for (let key3 of Object.keys(f)){
                                            let team = f[key3]
                                            if (key3 == seasonid){
                                                obj.teamAssists = team['totalAssist'];
                                            }
                                            else {
                                                continue;
                                            }
                                        }
                                    }
                                    else {
                                        continue;
                                    }
                                }
                            }*/
                            Result.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        Result = Result.sort(objectArraySort('assists'));
        let result = [], i = 1;
        for (let a of Result){
            if (i <= 15){
                a.rank = i;
                const p = await playerCtl.find({playerId: a.playerId});
                for (let b of p){
                    a.playerName = b.playerName;
                    a.playerImg = b.playerImg;
                }
                const t = await teamCtl.find({teamId: a['teamId']})
                for (let c of t){
                    for (let key4 of Object.keys(c['name'])){
                        if (key4 == seasonid){
                            let team = c['name'][key4]
                            a.teamName = team.offcialName.slice(0,4);
                            a.teamImg = team.teamImg;
                        }
                    }
                }
                const teamfeature = await teafeaCtl.find({teamId: a['teamId']});
                for (let d of teamfeature){
                    for (let key2 of Object.keys(d)){
                        if (key2 == competitionid){
                            let f = d[key2];
                            for (let key3 of Object.keys(f)){
                                let team = f[key3]
                                if (key3 == seasonid){
                                    a.teamAssists = team['totalAssist'];
                                }
                                else {
                                    continue;
                                }
                            }
                        }
                        else {
                            continue;
                        }
                    }
                }
                a.scoreRatio = (a.assists / a.teamAssists * 100).toFixed() + '%';
                result.push(a);
                /*let obj = {};
                obj.rank = i;
                obj.playerId = a.playerId;
                obj.playerName = a.playerName;
                obj.teamId = a.teamId;
                obj.teamName = a.teamName;
                obj.teamImg = a.teamImg;
                obj.assists = a.assists;
                obj.setAssists = a.setAssists;
                //obj.penalty = a.penalty;
                obj.teamAssists = a.teamAssists;
                obj.scoreRatio = (a.assists / a.teamAssists * 100).toFixed() + '%';
                result.push(obj);*/
                i++;
            }
            else {
                break;
            }
        }
        ctx.body = result;
    })

    .get('/matchInformation/:matchid', async (ctx, next)=>{
        const {matchid} = ctx.params;
        const matchinfor = await matchCtl.find({matchId: matchid});
        let result = {};//, goalsData = [], yellowCardData = [], redCardData = [], changeData = [], homeId = 0, awayId = 0;
        for (let a of matchinfor) {
            let battleTeam = {}, stadium = 0, city = 0;
            homeId = a.home_team_id;
            awayId = a.away_team_id;
            const hometeam = await teamCtl.find({teamId: a.home_team_id});
            for (let b of hometeam) {
                for (let key of Object.keys(b['name'])){
                    if (key == a.season){
                        let c = b['name'][key]
                        battleTeam.homeName = c.offcialName.slice(0,4);
                        //obj.teamShortName = b.teamName
                        battleTeam.homeTeamImg = c.teamImg;
                    }
                    else {
                        continue;
                    }
                }
                stadium = b.stadiumName;
                city = b.city;
            }
            const awayteam = await teamCtl.find({teamId: a.away_team_id});
            for (let b of awayteam) {
                for (let key of Object.keys(b['name'])){
                    if (key == a.season){
                        let c = b['name'][key]
                        battleTeam.awayName = c.offcialName.slice(0,4);
                        //obj.teamShortName = b.teamName
                        battleTeam.awayTeamImg = c.teamImg;
                    }
                    else {
                        continue;
                    }
                }
            }
            battleTeam.score = a.home_score + ':' + a.away_score;
            battleTeam.matchTime = a.match_time.slice(0,20);
            battleTeam.city = stadium + ',' + city;
            //matchTime = a.matchTime;
            result.battleTeam = battleTeam;
        }
        ctx.body = result;
    })

    .get('/matchInfor/:matchid', async (ctx, next)=>{
        const {matchid} = ctx.params;
        const matchinfor = await matchCtl.find({matchId: matchid});
        let result = {}, goalsData = [], yellowCardData = [], redCardData = [], changeData = [], homeId = 0, awayId = 0;
        for (let a of matchinfor) {
            homeId = a.home_team_id;
            awayId = a.away_team_id;
            /*const hometeam = await teamCtl.find({teamId: a.home_team_id});
            for (let b of hometeam) {
                for (let key of Object.keys(b['name'])){
                    if (key == a.season){
                        let c = b['name'][key]
                        battleTeam.homeName = c.offcialName.slice(0,4);
                        //obj.teamShortName = b.teamName
                        battleTeam.homeTeamImg = c.teamImg;
                    }
                    else {
                        continue;
                    }
                }
            }
            const awayteam = await teamCtl.find({teamId: a.away_team_id});
            for (let b of awayteam) {
                for (let key of Object.keys(b['name'])){
                    if (key == a.season){
                        let c = b['name'][key]
                        battleTeam.awayName = c.offcialName.slice(0,4);
                        //obj.teamShortName = b.teamName
                        battleTeam.awayTeamImg = c.teamImg;
                    }
                    else {
                        continue;
                    }
                }
            }
            battleTeam.score = a.home_score + ':' + a.away_score;
            //matchTime = a.matchTime;
            result.battleTeam = battleTeam;*/
            for (let key of Object.keys(a.formation)) {
                let sub = a.formation[key];
                for (let b of sub.Substitution) {
                    let obj = {};
                    obj.time = b.subTime;
                    obj.rate = ((b.subTime / a.matchTime || 0) * 100).toFixed(2) + '%';
                    const startplayer = await playerCtl.find({playerId: b.subPlayerId});
                    for (let c of startplayer) {
                        obj.start = c.playerName;
                        obj.startLogo = c.playerImg;
                    }
                    const subplayer = await playerCtl.find({playerId: b.playerId});
                    for (let c of subplayer) {
                        obj.sub = c.playerName;
                        obj.subLogo = c.playerImg;
                    }
                    changeData.push(obj);
                }
            }
            const events = await eventCtl.find({$or:[{type_id:8},{type_id:9},{type_id:10},{type_id:23},{type_id:24},{type_id:25}], match_id: matchid});
            //console.log(events)
            for (let b of events) {
                if (b.result_id == 2) {
                    let obj = {};
                    obj.time = b.minute;
                    obj.rate = ((b.minute / a.matchTime || 0) * 100).toFixed(2) + '%';
                    const player = await playerCtl.find({playerId: b.playerId});
                    for (let c of player) {
                        obj.player = c.playerName;
                        obj.playerLogo = c.playerImg;
                    }
                    goalsData.push(obj);
                }
                else if (b.type_id == 25 || b.type_id == 24) {
                    let obj = {};
                    obj.time = b.minute;
                    obj.rate = ((b.minute / a.matchTime || 0) * 100).toFixed(2) + '%';
                    const player = await playerCtl.find({playerId: b.playerId});
                    for (let c of player) {
                        obj.player = c.playerName;
                        obj.playerLogo = c.playerImg;
                    }
                    //console.log(obj);
                    yellowCardData.push(obj);
                }
                else if (b.type_id == 23) {
                    let obj = {};
                    obj.time = b.minute;
                    obj.rate = ((b.minute / a.matchTime || 0) * 100).toFixed(2) + '%';
                    const player = await playerCtl.find({playerId: b.playerId});
                    for (let c of player) {
                        obj.player = c.playerName;
                        obj.playerLogo = c.playerImg;
                    }
                    //console.log(obj);
                    redCardData.push(obj);
                }
                else {
                    continue;
                }
            }
        }
        const matches = await matchCtl.find({$or: [{home_team_id: homeId, away_team_id: awayId}, {home_team_id: awayId, away_team_id: homeId}]});
        let obj1 = {season: 2016}, obj2 = {season: 2017}, obj3 = {season: 2018}, obj4 = {season: 2019}, battle1 = [], battle2 = [], battle3 = [], battle4 = [];
        for (let a of matches) {
            if (a.season == 2016) {
                let obj = {}, stadium = 0, city = 0;
                obj.matchId = a.matchId;
                obj.homeTeamId = a.home_team_id;
                const hometeam1 = await teamCtl.find({teamId: a.home_team_id});
                for (let b of hometeam1) {
                    stadium = b.stadiumName;
                    city = b.city;
                    for (let key of Object.keys(b['name'])){
                        if (key == a.season){
                            let c = b['name'][key]
                            obj.homeTeam = c.offcialName.slice(0,4);
                            //obj.teamShortName = b.teamName
                            obj.homeTeamImg = c.teamImg;
                        }
                        else {
                            continue;
                        }
                    }
                }
                obj.awayTeamId = a.away_team_id;
                const awayteam1 = await teamCtl.find({teamId: a.away_team_id});
                for (let b of awayteam1) {
                    for (let key of Object.keys(b['name'])){
                        if (key == a.season){
                            let c = b['name'][key]
                            obj.awayTeam = c.offcialName.slice(0,4);
                            //obj.teamShortName = b.teamName
                            obj.awayTeamImg = c.teamImg;
                        }
                        else {
                            continue;
                        }
                    }
                }
                obj.score = a.home_score + '-' + a.away_score;
                obj.matchTime = a. match_time.slice(0,10);
                obj.stadium = stadium + ',' + city;
                battle1.push(obj);
            }
            else if (a.season == 2017) {
                let obj = {}, stadium = 0, city = 0;
                obj.matchId = a.matchId;
                obj.homeTeamId = a.home_team_id;
                const hometeam1 = await teamCtl.find({teamId: a.home_team_id});
                for (let b of hometeam1) {
                    stadium = b.stadiumName;
                    city = b.city;
                    for (let key of Object.keys(b['name'])){
                        if (key == a.season){
                            let c = b['name'][key]
                            obj.homeTeam = c.offcialName.slice(0,4);
                            //obj.teamShortName = b.teamName
                            obj.homeTeamImg = c.teamImg;
                        }
                        else {
                            continue;
                        }
                    }
                }
                obj.awayTeamId = a.away_team_id;
                const awayteam1 = await teamCtl.find({teamId: a.away_team_id});
                for (let b of awayteam1) {
                    for (let key of Object.keys(b['name'])){
                        if (key == a.season){
                            let c = b['name'][key]
                            obj.awayTeam = c.offcialName.slice(0,4);
                            //obj.teamShortName = b.teamName
                            obj.awayTeamImg = c.teamImg;
                        }
                        else {
                            continue;
                        }
                    }
                }
                obj.score = a.home_score + '-' + a.away_score;
                obj.matchTime = a. match_time.slice(0,10);
                obj.stadium = stadium + ',' + city;
                battle2.push(obj);
            }
            else if (a.season == 2018) {
                let obj = {}, stadium = 0, city = 0;
                obj.matchId = a.matchId;
                obj.homeTeamId = a.home_team_id;
                const hometeam1 = await teamCtl.find({teamId: a.home_team_id});
                for (let b of hometeam1) {
                    stadium = b.stadiumName;
                    city = b.city;
                    for (let key of Object.keys(b['name'])){
                        if (key == a.season){
                            let c = b['name'][key]
                            obj.homeTeam = c.offcialName.slice(0,4);
                            //obj.teamShortName = b.teamName
                            obj.homeTeamImg = c.teamImg;
                        }
                        else {
                            continue;
                        }
                    }
                }
                obj.awayTeamId = a.away_team_id;
                const awayteam1 = await teamCtl.find({teamId: a.away_team_id});
                for (let b of awayteam1) {
                    for (let key of Object.keys(b['name'])){
                        if (key == a.season){
                            let c = b['name'][key]
                            obj.awayTeam = c.offcialName.slice(0,4);
                            //obj.teamShortName = b.teamName
                            obj.awayTeamImg = c.teamImg;
                        }
                        else {
                            continue;
                        }
                    }
                }
                obj.score = a.home_score + '-' + a.away_score;
                obj.matchTime = a. match_time.slice(0,10);
                obj.stadium = stadium + ',' + city;
                battle3.push(obj);
            }
            else if (a.season == 2019) {
                let obj = {}, stadium = 0, city = 0;
                obj.matchId = a.matchId;
                obj.homeTeamId = a.home_team_id;
                const hometeam1 = await teamCtl.find({teamId: a.home_team_id});
                for (let b of hometeam1) {
                    stadium = b.stadiumName;
                    city = b.city;
                    for (let key of Object.keys(b['name'])){
                        if (key == a.season){
                            let c = b['name'][key]
                            obj.homeTeam = c.offcialName.slice(0,4);
                            //obj.teamShortName = b.teamName
                            obj.homeTeamImg = c.teamImg;
                        }
                        else {
                            continue;
                        }
                    }
                }
                obj.awayTeamId = a.away_team_id;
                const awayteam1 = await teamCtl.find({teamId: a.away_team_id});
                for (let b of awayteam1) {
                    for (let key of Object.keys(b['name'])){
                        if (key == a.season){
                            let c = b['name'][key]
                            obj.awayTeam = c.offcialName.slice(0,4);
                            //obj.teamShortName = b.teamName
                            obj.awayTeamImg = c.teamImg;
                        }
                        else {
                            continue;
                        }
                    }
                }
                obj.score = a.home_score + '-' + a.away_score;
                obj.matchTime = a. match_time.slice(0,10);
                obj.stadium = stadium + ',' + city;
                battle4.push(obj);
            }
            else {
                continue;
            } 
        }
        obj1.battle = battle1;
        obj2.battle = battle2;
        obj3.battle = battle3;
        obj4.battle = battle4;
        let battleRecord = [];
        battleRecord.push(obj1);
        battleRecord.push(obj2);
        battleRecord.push(obj3);
        battleRecord.push(obj4);
        let matchProcess = {};
        matchProcess.goalsData = goalsData;
        matchProcess.yellowCardData = yellowCardData;
        matchProcess.redCardData = redCardData;
        matchProcess.changeData = changeData;
        result.matchProcess = matchProcess;
        result.battleRecord = battleRecord;
        ctx.body = result;
    })

    .get('/matchPlayer/:matchid', async (ctx, next)=>{
        const {matchid} = ctx.params;
        const match = await matchCtl.find({matchId: matchid});
        const events = await eventCtl.find({$or:[{result_id:2},{result_id:3},{type_id:23},{type_id:24},{type_id:25}], match_id: matchid});
        let result = [], homeplayer = [], awayplayer = [];
        for (let a of match) {
            for (let key of Object.keys(a.formation)) {
                //console.log(key)
                let player = a.formation[key];
                for (let b of player.Lineup) {
                    //console.log(b)
                    let obj = {}, cards = [], goal = [];
                    for (let c of player.Substitution) {
                        //console.log(c)
                        if (c.subPlayerId == b.playerId) {
                            obj.appearance = 1;
                            obj.minutes = c.subTime;
                            break;
                        }
                        else {
                            obj.appearance = 0;
                            obj.minutes = a.matchTime;
                        }
                    }
                    obj.playerId = b.playerId;
                    const playerinfor = await playerCtl.find({playerId: b.playerId});
                    for (let c of playerinfor) {
                        for (let key1 of Object.keys(c.team)) {
                            if (key1 == a.season) {
                                obj.number = c.team[key1].teamNum;
                            }
                            else {
                                continue;
                            }
                        }
                        obj.playerName = c.playerName;
                        obj.playerImg = c.playerImg;
                        switch (c.role) {
                            case 'GK':
                                obj.position = '门将';
                                break;
                            case 'DF':
                                obj.position = '后卫';
                                break;
                            case 'MF':
                                obj.position = '中场';
                                break;
                            case 'ST':
                                obj.position = '前锋';
                                break;
                            default:
                                break;
                        }
                    }
                    //const events = await eventCtl.find({$or:[{result_id:2},{result_id:3},{type_id:23},{type_id:24},{type_id:25}], match_id: matchid, playerId: b.playerId});
                    for (let c of events) {
                        if ((c.type_id == 24 || c.type_id == 25) && c.playerId == b.playerId) {
                            let obj = {};
                            obj.time = c.minute;
                            obj.type = 'yellow';
                            cards.push(obj);
                        }
                        else if ((c.type_id == 23) && c.playerId == b.playerId) {
                            let obj = {};
                            obj.time = c.minute;
                            obj.type = 'red';
                            cards.push(obj);
                        }
                        else if ((c.result_id == 2) && c.playerId == b.playerId) {
                            let obj = {};
                            obj.time = c.minute;
                            obj.type = 'goal';
                            switch (c.bodypart_name) {
                                case 'Left':
                                    obj.body = '左脚';
                                    break;
                                case 'Right':
                                    obj.body = '右脚';
                                    break;
                                case 'Head':
                                    obj.body = '头球';
                                    break;
                                case 'Foot':
                                    obj.body = '其他';
                                    break;
                                default:
                                    break;
                            }
                            goal.push(obj);
                        }
                        else if ((c.result_id == 3) && c.playerId == b.playerId) {
                            let obj = {};
                            obj.time = c.minute;
                            obj.type = 'ownGoal';
                            obj.body = '乌龙球';
                            goal.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                    obj.cards = cards;
                    obj.goal = goal;
                    if (key == a.home_team_id) {
                        homeplayer.push(obj);
                    }
                    else {
                        awayplayer.push(obj);
                    }
                }
                for (let b of player.Substitution) {
                    let obj = {}, cards = [], goal = [];
                    obj.appearance = 2;
                    obj.minutes = a.matchTime - b.subTime;
                    obj.playerId = b.playerId;
                    const playerinfor = await playerCtl.find({playerId: b.playerId});
                    for (let c of playerinfor) {
                        for (let key1 of Object.keys(c.team)) {
                            if (key1 == a.season) {
                                obj.number = c.team[key1].teamNum;
                            }
                            else {
                                continue;
                            }
                        }
                        obj.playerName = c.playerName;
                        obj.playerImg = c.playerImg;
                        switch (c.role) {
                            case 'GK':
                                obj.position = '门将';
                                break;
                            case 'DF':
                                obj.position = '后卫';
                                break;
                            case 'MF':
                                obj.position = '中场';
                                break;
                            case 'ST':
                                obj.position = '前锋';
                                break;
                            default:
                                break;
                        }
                    }
                    //const events = await eventCtl.find({$or:[{result_id:2},{result_id:3},{type_id:23},{type_id:24},{type_id:25}], match_id: matchid, playerId: b.playerId});
                    for (let c of events) {
                        if ((c.type_id == 24 || c.type_id == 25) && c.playerId == b.playerId) {
                            let obj = {};
                            obj.time = c.minute;
                            obj.type = 'yellow';
                            cards.push(obj);
                        }
                        else if ((c.type_id == 23) && c.playerId == b.playerId) {
                            let obj = {};
                            obj.time = c.minute;
                            obj.type = 'red';
                            cards.push(obj);
                        }
                        else if ((c.result_id == 2) && c.playerId == b.playerId) {
                            let obj = {};
                            obj.time = c.minute;
                            obj.type = 'goal';
                            switch (c.bodypart_name) {
                                case 'Left':
                                    obj.body = '左脚';
                                    break;
                                case 'Right':
                                    obj.body = '右脚';
                                    break;
                                case 'Head':
                                    obj.body = '头球';
                                    break;
                                case 'Foot':
                                    obj.body = '其他';
                                    break;
                                default:
                                    break;
                            }
                            goal.push(obj);
                        }
                        else if ((c.result_id == 3) && c.playerId == b.playerId) {
                            let obj = {};
                            obj.time = c.minute;
                            obj.type = 'ownGoal';
                            obj.body = '乌龙球';
                            goal.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                    obj.cards = cards;
                    obj.goal = goal;
                    if (key == a.home_team_id) {
                        homeplayer.push(obj);
                    }
                    else {
                        awayplayer.push(obj);
                    }
                }
            }
        }
        result.push(homeplayer);
        result.push(awayplayer);
        ctx.body = result;
    })

    .get('/matchIndicator/:matchid', async (ctx, next)=>{
        const {matchid} = ctx.params;
        const events = await eventCtl.find({match_id: matchid});
        const match = await matchCtl.find({matchId: matchid});
        let result = [], allBattle = {}, attackBattle = {}, defenseBattle = {};
        let home1 = {goals: 0, shots: 0, shotsOnTarget: 0, passes: 0, passesAccuracy: 0, setPiece: 0, corner: 0};
        let home2 = {createChance: 0, keyPass: 0, throughPass: 0, crosses: 0, attackBoxPass: 0, accuracy: 0, offside: 0};
        let home3 = {interception: 0, tackle: 0, clearance: 0, fouls: 0, yellow: 0, red: 0, blockPass: 0, blockShot: 0};
        let away1 = {goals: 0, shots: 0, shotsOnTarget: 0, passes: 0, passesAccuracy: 0, setPiece: 0, corner: 0};
        let away2 = {createChance: 0, keyPass: 0, throughPass: 0, crosses: 0, attackBoxPass: 0, accuracy: 0, offside: 0};
        let away3 = {interception: 0, tackle: 0, clearance: 0, fouls: 0, yellow: 0, red: 0, blockPass: 0, blockShot: 0};
        let hpacc = 0, apacc = 0;
        let hpbacc = 0, apbacc = 0;
        for (let a of match) {
            for (let b of events) {
                if (b.teamId == a.home_team_id){
                    if (b.result_id == 2) {
                        home1.goals = home1.goals + 1;
                        home1.shotsOnTarget = home1.shotsOnTarget + 1;
                    }
                    else if (b.result_id == 3) {
                        away1.goals = away1.goals + 1;
                    }
                    if (b.type_id == 8 || b.type_id == 9 || b.type_id == 10) {
                        home1.shots = home1.shots + 1;
                        if (b.result_id == 6) {
                            home1.shotsOnTarget = home1.shotsOnTarget + 1;
                        }
                        else {
                            continue;
                        }
                    }
                    else if (b.type_id == 0 || b.type_id == 1 || b.type_id == 2 || b.type_id == 3 || b.type_id == 4 || b.type_id == 5 || b.type_id == 6 || b.type_id == 7) {
                        home1.passes = home1.passes + 1;
                        if (b.result_id != 1) {
                            hpacc++;
                            home1.passesAccuracy = parseFloat((hpacc / home1.passes || 0).toFixed(2));
                        }
                        if (b.result_id == 4 || b.result_id == 5) {
                            home2.createChance = home2.createChance + 1;
                            if (b.result_id == 5) {
                                home2.keyPass = home2.keyPass + 1;
                            }
                            else {
                                continue;
                            }
                        }
                        if (b.attribute_id == 0) {
                            home2.throughPass = home2.throughPass + 1;
                        }
                        if (b.type_id == 5 || b.type_id == 6 || b.type_id == 7) {
                            home2.crosses = home2.crosses + 1;
                        }
                        if (b.x >= 89 && b.y >= 14 && b.y <= 54) {
                            home2.attackBoxPass = home2.attackBoxPass + 1;
                            if (b.result_id != 1) {
                                hpbacc++;
                                home2.accuracy = parseFloat((hpbacc / home2.attackBoxPass || 0).toFixed(2));
                            }
                            else {
                                continue;
                            }
                        }
                    }
                    else if (b.type_id == 4 || b.type_id == 6 || b.type_id == 7 || b.type_id == 9 || b.type_id == 11) {
                        home1.setPiece = home1.setPiece + 1;
                        if (b.type_id == 7 || b.type_id == 11) {
                            home1.corner = home1.corner + 1;
                        }
                        else {
                            continue;
                        }
                    }
                    else if (b.type_id == 34) {
                        home2.offside = home2.offside + 1;
                    }
                    else if (b.type_id == 15) {
                        home3.interception = home3.interception + 1;
                    }
                    else if (b.type_id == 16) {
                        home3.tackle = home3.tackle + 1;
                    }
                    else if (b.type_id == 14) {
                        home3.clearance = home3.clearance + 1;
                    }
                    else if (b.type_id == 20 || b.type_id == 21) {
                        home3.fouls = home3.fouls + 1;
                    }
                    else if (b.type_id == 24 || b.type_id == 25) {
                        home3.yellow = home3.yellow + 1;
                    }
                    else if (b.type_id == 23) {
                        home3.red = home3.red + 1;
                    }
                    else if (b.type_id == 18) {
                        home3.blockPass = home3.blockPass + 1;
                    }
                    else if (b.type_id == 19) {
                        home3.blockShot = home3.blockShot + 1;
                    }
                    else {
                        continue;
                    }
                }
                else if(b.teamId == a.away_team_id){
                    if (b.result_id == 2) {
                        away1.goals = away1.goals + 1;
                        away1.shotsOnTarget = away1.shotsOnTarget + 1;
                    }
                    else if (b.result_id == 3) {
                        home1.goals = home1.goals + 1;
                    }
                    if (b.type_id == 8 || b.type_id == 9 || b.type_id == 10) {
                        away1.shots = away1.shots + 1;
                        if (b.result_id == 6) {
                            away1.shotsOnTarget = away1.shotsOnTarget + 1;
                        }
                        else {
                            continue;
                        }
                    }
                    else if (b.type_id == 0 || b.type_id == 1 || b.type_id == 2 || b.type_id == 3 || b.type_id == 4 || b.type_id == 5 || b.type_id == 6 || b.type_id == 7) {
                        away1.passes = away1.passes + 1;
                        if (b.result_id != 1) {
                            apacc++;
                            away1.passesAccuracy = parseFloat((apacc / away1.passes || 0).toFixed(2));
                        }
                        if (b.result_id == 4 || b.result_id == 5) {
                            away2.createChance = away2.createChance + 1;
                            if (b.result_id == 5) {
                                away2.keyPass = away2.keyPass + 1;
                            }
                            else {
                                continue;
                            }
                        }
                        if (b.attribute_id == 0) {
                            away2.throughPass = away2.throughPass + 1;
                        }
                        if (b.type_id == 5 || b.type_id == 6 || b.type_id == 7) {
                            away2.crosses = away2.crosses + 1;
                        }
                        if (b.x >= 89 && b.y >= 14 && b.y <= 54) {
                            away2.attackBoxPass = away2.attackBoxPass + 1;
                            if (b.result_id != 1) {
                                apbacc++;
                                away2.accuracy = parseFloat((apbacc / away2.attackBoxPass || 0).toFixed(2));
                            }
                            else {
                                continue;
                            }
                        }
                    }
                    else if (b.type_id == 4 || b.type_id == 6 || b.type_id == 7 || b.type_id == 9 || b.type_id == 11) {
                        away1.setPiece = away1.setPiece + 1;
                        if (b.type_id == 7 || b.type_id == 11) {
                            away1.corner = away1.corner + 1;
                        }
                        else {
                            continue;
                        }
                    }
                    else if (b.type_id == 34) {
                        away2.offside = away2.offside + 1;
                    }
                    else if (b.type_id == 15) {
                        away3.interception = away3.interception + 1;
                    }
                    else if (b.type_id == 16) {
                        away3.tackle = away3.tackle + 1;
                    }
                    else if (b.type_id == 14) {
                        away3.clearance = away3.clearance + 1;
                    }
                    else if (b.type_id == 20 || b.type_id == 21) {
                        away3.fouls = away3.fouls + 1;
                    }
                    else if (b.type_id == 24 || b.type_id == 25) {
                        away3.yellow = away3.yellow + 1;
                    }
                    else if (b.type_id == 23) {
                        away3.red = away3.red + 1;
                    }
                    else if (b.type_id == 18) {
                        away3.blockPass = away3.blockPass + 1;
                    }
                    else if (b.type_id == 19) {
                        away3.blockShot = away3.blockShot + 1;
                    }
                    else {
                        continue;
                    }
                }
                else {
                    continue;
                }
            }
        }
        allBattle.behavior0 = home1;
        allBattle.behavior1 = away1;
        attackBattle.behavior0 = home2;
        attackBattle.behavior1 = away2;
        defenseBattle.behavior0 = home3;
        defenseBattle.behavior1 = away3;
        result.push(allBattle);
        result.push(attackBattle);
        result.push(defenseBattle);
        ctx.body = result;
    })

    .get('/matchPerformance/:matchid', async (ctx, next)=>{
        const {matchid} = ctx.params;
        const events = await eventCtl.find({match_id: matchid});
        const match = await matchCtl.find({matchId: matchid});
        let result = [], homeplayers = [], homeplayersRating = [], awayplayers = [], awayplayersRating = [];
        for (let a of match) {
            for (let key of Object.keys(a.formation)) {
                //console.log(key)
                let player = a.formation[key];
                for (let b of player.Lineup) {
                    let obj = {}, obj1 = {}, x = 0, y = 0, i = 0;
                    obj.playerId = b.playerId;
                    const playerinfor = await playerCtl.find({playerId: b.playerId});
                    for (let c of playerinfor) {
                        for (let key1 of Object.keys(c.team)) {
                            if (key1 == a.season) {
                                obj.number = c.team[key1].teamNum;1362804
                                obj1.number = c.team[key1].teamNum;
                            }
                            else {
                                continue;
                            }
                        }
                        obj.playerName = c.playerName;
                        obj.playerImg = c.playerImg;
                    }
                    obj.rating = parseFloat((b.totalScore).toFixed(2));
                    obj.type = b.type;
                    //playersRating.push(obj);
                    for (let c of events) {
                        if (c.playerId == b.playerId) {
                            x = x + c.x;
                            y = y + c.y;
                            i++;
                        }
                        else {
                            continue;
                        }
                    }
                    obj1.x1 = ((x / i) / 105 * 100).toFixed(2) + '%';
                    obj1.y1 = ((y / i) / 68 * 100).toFixed(2) + '%';
                    if (key == a.home_team_id) {
                        homeplayersRating.push(obj);
                        homeplayers.push(obj1);
                    }
                    else {
                        awayplayersRating.push(obj);
                        awayplayers.push(obj1);
                    }
                    //players.push(obj1);
                }
                for (let b of player.Substitution) {
                    let obj = {}, obj1 = {}, x = 0, y = 0, i = 0;
                    obj.playerId = b.playerId;
                    const playerinfor = await playerCtl.find({playerId: b.playerId});
                    for (let c of playerinfor) {
                        for (let key1 of Object.keys(c.team)) {
                            if (key1 == a.season) {
                                obj.number = c.team[key1].teamNum;
                                obj1.number = c.team[key1].teamNum;
                            }
                            else {
                                continue;
                            }
                        }
                        obj.playerName = c.playerName;
                        obj.playerImg = c.playerImg;
                    }
                    obj.rating = parseFloat((b.totalScore).toFixed(2));
                    obj.type = b.type;
                    //playersRating.push(obj);
                    for (let c of events) {
                        if (c.playerId == b.playerId) {
                            x = x + c.x;
                            y = y + c.y;
                            i++;
                        }
                        else {
                            continue;
                        }
                    }
                    obj1.x1 = ((x / i) / 105 * 100).toFixed(2) + '%';
                    obj1.y1 = ((y / i) / 68 * 100).toFixed(2) + '%';
                    //players.push(obj1);
                    if (key == a.home_team_id) {
                        homeplayersRating.push(obj);
                        homeplayers.push(obj1);
                    }
                    else {
                        awayplayersRating.push(obj);
                        awayplayers.push(obj1);
                    }
                }
            }
        }
        let home_players = {}, away_players = {};
        home_players.players = homeplayers;
        home_players.playersRating = homeplayersRating;
        away_players.players = awayplayers;
        away_players.playersRating = awayplayersRating;
        result.push(home_players);
        result.push(away_players);
        ctx.body = result;
    })

    /*.get('/prematch/playerlists/:matchid', async (ctx, next)=>{
        const {matchid} = ctx.params;
        const r = await matchCtl.retrieve(matchid);
        let result = {}; let i = 0;
        for (let key of Object.keys(r.teamsData)){
            let p = 0; let w = 0; let d = 0; let l = 0;
            i++;
            let t = r.teamsData[key];
            const team = await teamCtl.retrieve(t.teamId);
            for (let a of team){
                if (i == 1){
                    //result.teamOne = a.name;
                    result.teamOneLogo = a.countryImg;
                }
                else if (i == 2){
                    //result.teamTwo = a.name;
                    result.teamTwoLogo = a.countryImg;
                }
                const matches = await MtmCtl.find({teamId: t.teamId, Date: {$lt: r.dateutc}})
                //console.log(matches);
                result[a.name + ' PLAYER LIST'] = [];
                const players = await playerCtl.find({currentNationalTeamId: t.teamId})
                for (let b of players){
                    let obj ={};
                    obj.playerId = b.wyId;
                    obj.number = b.countryNumber;
                    obj.name = b.shortName;
                    obj.Role = b['role'].code3;
                    obj.Nationality = b.countryLogo;
                    obj.Age = 2018-(b.birthDate).substring(0,4);
                    result[a.name + ' PLAYER LIST'].push(obj)
                    //console.log(result[a.name + ' PLAYER LIST'])
                }
                for (let b of result[a.name + ' PLAYER LIST']){
                    let m = 0; let g = 0; let mp = 0;
                    for (let c of matches){
                        const matchplayer = await MplCtl.find({matchId: c.matchId, playerId: b.playerId})
                        for (let d of matchplayer){
                            if (d.playTime > 0){
                                m++;
                                mp+=d.playTime;
                                g+=d.Goal.allMatch;
                            }
                            else {continue;}
                        }
                        /**const eventplayer = await eventCtl.find({matchId: c.matchId, playerId: b.playerId, $or:[{eventId:10},{eventId:3}]})
                        for (let d of eventplayer){
                            for (let tag of d.tags){
                                if (tag.id == 101){
                                    g++;
                                }
                                else {continue;}
                            }
                        }
                    }
                    b.Matches = m;
                    b.Goals = g;
                    b['Minutes played'] = mp;
                }
                for (let b of matches){
                    p++;
                    const match = await matchCtl.retrieve(b.matchId);
                    if (match.winner == (t.teamId).substring(2,10)){
                        w++;
                    }
                    else if (match.winner == 0){
                        d++;
                    }
                    else {l++};
                }
                //console.log(w);
                result[a.name + ' COACH'] = []
                const coach = await coachCtl.retrieve(a.coachId);
                //console.log(coach);
                let obj = {};
                obj.name = coach.shortName;
                obj.birthdate = coach.birthDate;
                obj.P = p;
                obj.W = w;
                obj.D = d;
                obj.L = l;
                result[a.name + ' COACH'].push(obj);
            }
        }
        ctx.body = result;
    })*/



module.exports = router;

/**
 * @swagger
 * resourcePath: /api
 * description: All about API
 * definitions:
 *   match:
 *     type: "object"
 *     required:
 *       - "name"
 *     properties:
 *       wyId:
 *         type: "string"
 *       status:
 *         type: "string"
 *       roundId:
 *         type: "string"
 *       gameweek:
 *         type: "number"
 *       seasonId:
 *         type: "string"
 *       dateutc: 
 *         type: "string" 
 *       winner: 
 *         type: "number"
 *       venue: 
 *         type: "string"
 *       label: 
 *         type: "string"
 *       date: 
 *         type: "string"
 *       duration: 
 *         type: "string"
 *       competitionId: 
 *         type: "string"
 */